<template>
  <div class="view-fill">
    <div v-show="!assetDetailInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button
            :disabled="!canSave"
            @click="save(true)"
            v-if="!orderId && $permission('assetReturn:saveAndSubmit')"
            >保存并提交</el-button
          >
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-checkReturn>
                <el-radio-group
                  v-model="formInfo.data.locationType"
                  @change="changeRadio"
                >
                  <el-radio label="1">部门</el-radio>
                  <el-radio label="2">仓库</el-radio>
                </el-radio-group>
              </template>
              <template v-slot:form-deptName>
                <el-input
                  v-model="formInfo.data.deptName"
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择部门"
                >
                  <template #append>
                    <el-icon @click="openDeptWindow"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-depotName>
                <el-input
                  v-model="formInfo.data.depotName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择出库仓库"
                >
                  <template #append>
                    <el-icon @click="selectDepot"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-supplierName>
                <el-input
                  v-model="formInfo.data.supplierName"
                  class="not-br not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择供应商"
                >
                  <template #append>
                    <el-icon @click="openSupplierWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-addAsset>
                <el-button :disabled="!canAdd" @click="addAsset"
                  >添加资产</el-button
                >
              </template>
              <template v-slot:filter-removeAsset>
                <el-button :disabled="!canRemoveAsset" @click="removeAsset()"
                  >删除资产</el-button
                >
              </template>
              <template v-slot:filter-assetCodeScan>
                <ScanInputBox
                  :query="scanInfo.query"
                  :disabled="!canAdd"
                  @callback="onCallBackScanData"
                />
              </template>
            </page-filter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-assetName="scope">
                    <span
                      class="slip-edit"
                      @click="showAssetDetail(scope.row)"
                      >{{ scope.row.assetName }}</span
                    >
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!--部门选择框-->
    <select-dept
      v-if="selectDeptInfo.visible"
      v-model:show-dialog="selectDeptInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="selectDeptInfo.query"
      :save-empty="true"
      @callback="selectDeptCallback"
    />
    <!-- 添加资产 -->
    <Select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      :check-box="true"
      table-key="assetAssetReturnAddAsset-com.slip.spd.entity.vo.core.CoreAssetVO"
      @callback="callBackAsset"
    />
    <!-- 详情页 -->
    <asset-card-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      :title="assetDetailInfo.title"
    />
    <SelectDepot
      v-if="selectDepotInfo.visible"
      v-model:show-dialog="selectDepotInfo.visible"
      :check-box="false"
      :query="selectDepotInfo.query"
      :highlight-row="true"
      :check-lock="true"
      :save-empty="true"
      @callback="selectDepotCallBack"
    />
    <select-supplier
      v-if="selectSupplierInfo.visible"
      v-model:show-dialog="selectSupplierInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="selectSupplierInfo.query"
      @callback="selectSupplierCallback"
    />
  </div>
</template>

<script setup name="AssetTransferModify">
import { getCustomizeSetting } from '@/api/customize'
import {
  updateAssetReturn,
  craterAssetReturn,
  craterAssetReturnAndSave,
  getAssetReturnById,
  assetReturnDetailCustomizeListAll,
} from '@/api/asset'
import { getCurrentFiscalPeriod } from '@/api/core'

import moment from 'moment'
import ScanInputBox from '@/components/SelectAsset/ScanInputBox'
const AssetCardDetail = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetCard/details')
)

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'title', 'orderId'])

const scanInfo = ref({
  query: {
    deptId: '',
    depotId: '',
    supplierId: '',
    assetStatus: 1,
    assetSourceAuth: true,
  },
})
//表单相关
const formInfo = ref({
  ref: null,
  data: {
    deptName: '',
    deptId: '',
    depotName: '',
    depotId: '',
    supplierName: '',
    supplierId: '',
    locationType: '1',
  },
  fieldList: [
    { label: '存放位置', value: 'checkReturn', type: 'slot' },
    { label: '退货部门', value: 'deptName', type: 'slot', show: true },
    { label: '退货仓库', value: 'depotName', type: 'slot', show: false },
    { label: '供应商', value: 'supplierName', type: 'slot' },
    { label: '供应商联系人', value: 'contact', type: 'input' },
    { label: '供应商联系电话', value: 'phone', type: 'input' },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      labelTip: '',
      TimePickerOptions: {},
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  rules: {
    deptName: [
      { required: true, message: '请选择退货部门', trigger: 'change' },
    ],
    depotName: [
      { required: true, message: '请选择退货仓库', trigger: 'change' },
    ],
    supplierName: [
      { required: true, message: '请选供应商', trigger: 'change' },
    ],
    businessDate: [
      { required: true, message: '请选择业务日期', trigger: 'blur' },
    ],
    phone: [{ validator: proxy.$validate.cellphone, trigger: 'blur' }],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      joinDepotStock: 'YES',
    },
  },
  list: [
    { type: 'slot', value: 'addAsset' },
    { type: 'slot', value: 'removeAsset' },
    { type: 'slot', value: 'assetCodeScan' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeAsset,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const selectDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
    status: 1,
    deptId: '',
  },
})
const selectAssetInfo = ref({
  visible: false,
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      assetSourceAuth: {
        asTbName: 'core_asset,core_asset',
        columnName: 'use_dept_id,depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'assetSourceAuth',
      },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '3',
      },
      assetStatus: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      isLocked: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      supplierId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      productId: {
        queryType: 'NOT_EQUAL',
        queryCategory: 'AND',
        value: '-2',
      },
    },
    queryParams: {
      useDeptIdMult: '',
    },
  },
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
  title: '资产详情',
})
const selectDepotInfo = ref({
  visible: false,
  query: {
    depotAuth: 'id',
    status: 1,
    useTypeId: 2,
  },
})
const selectSupplierInfo = ref({
  visible: false,
  query: {
    searchType: 'org',
    searchField: 'supplierId',
    supplierAuth: 'supplierId',
  },
})
const formRefs = ref([])

const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canAdd = computed(() => {
  return (
    (formInfo.value.data.deptId || formInfo.value.data.depotId) &&
    formInfo.value.data.supplierId
  )
})
const canRemoveAsset = computed(() => {
  return tableInfo.value.selections.length
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  proxy.$nextTick(() => {
    if (!props.orderId) {
      formInfo.value.fieldList = formInfo.value.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
})

setData()
function setData() {
  let obj = {}
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
  getFiscalPeriod()
}
function getFiscalPeriod() {
  getCurrentFiscalPeriod(2).then((res) => {
    if (res && res.success) {
      let index = formInfo.value.fieldList.findIndex(
        (item) => item.value === 'businessDate'
      )
      let fiscalPeriodName = res.data.name
      if (index > -1) {
        formInfo.value.fieldList[
          index
        ].labelTip = `当前会计期间：${fiscalPeriodName}`
        formInfo.value.fieldList[index].TimePickerOptions = {
          disabledDate(time) {
            return (
              time.getTime() <
              new Date(res.data.startDate).getTime() - 24 * 60 * 60 * 1000
            )
          },
        }
      }
    }
  })
}
function selectDepot() {
  selectDepotInfo.value.visible = true
}
function selectDepotCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.value.data.depotId = data.id
    scanInfo.value.query.depotId = data.id
    formInfo.value.data.depotName = data.name
    tableInfo.value.data = []
  } else {
    formInfo.value.data.depotId = ''
    formInfo.value.data.depotName = ''
    scanInfo.value.query.depotId = ''
    tableInfo.value.data = []
  }
}
function openSupplierWindow() {
  //选择供应商
  selectSupplierInfo.value.visible = true
}
function selectSupplierCallback(data) {
  //选择供应商发回
  if (data.supplierId) {
    formInfo.value.data['supplierId'] = data.supplierId
    formInfo.value.data['supplierName'] = data.supplierName
    formInfo.value.data['contact'] = data.contact
    formInfo.value.data['phone'] = data.contactNumber
    scanInfo.value.query.supplierId = data.supplierId
    tableInfo.value.data = []
  } else {
    formInfo.value.data['supplierId'] = ''
    formInfo.value.data['supplierName'] = ''
    formInfo.value.data['contact'] = ''
    formInfo.value.data['phone'] = ''
    scanInfo.value.query.supplierId = ''
    tableInfo.value.data = []
  }
}
function openDeptWindow() {
  selectDeptInfo.value.visible = true
}
function selectDeptCallback(row) {
  if (row && row.id) {
    formInfo.value.data['deptName'] = row.name
    formInfo.value.data['deptId'] = row.id
    scanInfo.value.query['deptId'] = row.id
    tableInfo.value.data = []
  } else {
    formInfo.value.data['deptName'] = ''
    formInfo.value.data['deptId'] = ''
    scanInfo.value.query['deptId'] = ''
    tableInfo.value.data = []
  }
}
function changeRadio(val) {
  formInfo.value.data.depotName = ''
  formInfo.value.data.depotId = ''
  formInfo.value.data.deptName = ''
  formInfo.value.data.deptId = ''
  scanInfo.value.query.deptId = ''
  scanInfo.value.query.depotId = ''
  tableInfo.value.data = []
  if (val === '1') {
    showFieldListItem(true, 'deptName')
    showFieldListItem(false, 'depotName')
    selectAssetInfo.value.query.queryMap.assetStatus.value = 1
    scanInfo.value.query.assetStatus = 1
  } else if (val === '2') {
    showFieldListItem(false, 'deptName')
    showFieldListItem(true, 'depotName')
    selectAssetInfo.value.query.queryMap.assetStatus.value = 3
    scanInfo.value.query.assetStatus = 3
  }
}
function showFieldListItem(show, nameValue) {
  let fieldList = formInfo.value.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function showAssetDetail(row) {
  assetDetailInfo.value.id = row.assetId
  assetDetailInfo.value.visible = true
}
function getMain() {
  getAssetReturnById(props.orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      formInfo.value.data.locationType =
        formInfo.value.data.locationType.toString()
      scanInfo.value.query.deptId =
        resp.data.deptId === -2 ? '' : resp.data.deptId
      scanInfo.value.query.depotId =
        resp.data.depotId === -2 ? '' : resp.data.depotId
      scanInfo.value.query.supplierId = resp.data.supplierId
      if (resp.data.locationType === '1') {
        showFieldListItem(true, 'deptName')
        showFieldListItem(false, 'depotName')
        selectAssetInfo.value.query.queryMap.assetStatus.value = 1
        scanInfo.value.query.assetStatus = 1
      } else if (resp.data.locationType === '2') {
        showFieldListItem(false, 'deptName')
        showFieldListItem(true, 'depotName')
        selectAssetInfo.value.query.queryMap.assetStatus.value = 3
        scanInfo.value.query.assetStatus = 3
      }
    }
  })
  filterInfo.value.query.queryMap.orderId.value = props.orderId
  getList()
}
function getList() {
  assetReturnDetailCustomizeListAll(filterInfo.value.query).then((res) => {
    if (res && res.success && res.data.length) {
      tableInfo.value.data = res.data
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function save(isSaveAndSubmit) {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let api = props.orderId
      ? updateAssetReturn
      : isSaveAndSubmit === true
      ? craterAssetReturnAndSave
      : craterAssetReturn
    let param = {
      ...formInfo.value.data,
      details: tableInfo.value.data,
    }
    api(param).then((res) => {
      if (res && res.success) {
        showDialog.value = false
        emits('returnModify', false)
      }
    })
  })
}
//选择资产
function addAsset() {
  selectAssetInfo.value.query.queryParams.useDeptIdMult =
    formInfo.value.data.deptId == -2 ? '' : formInfo.value.data.deptId || ''
  selectAssetInfo.value.query.queryMap.depotId.value =
    formInfo.value.data.depotId === -2 ? '' : formInfo.value.data.depotId || ''
  selectAssetInfo.value.query.queryMap.supplierId.value =
    formInfo.value.data.supplierId
  if (tableInfo.value.data.length) {
    selectAssetInfo.value.query.queryMap.id.value = tableInfo.value.data
      .map((item) => item.assetId)
      .toString()
  } else {
    selectAssetInfo.value.query.queryMap.id.value = ''
  }
  selectAssetInfo.value.visible = true
}
function onCallBackScanData(data, callback) {
  if (data && data.assetCode) {
    data.assetId = data.id
    if (tableInfo.value.data) {
      tableInfo.value.data.forEach((item) => {
        item.isChoice = false
      })
      let index = tableInfo.value.data.findIndex(
        (item) => item.assetCode === data.assetCode
      )
      if (index !== -1) {
        callback(true)
      } else {
        tableInfo.value.data.unshift(data)
        callback(false)
      }
    } else {
      tableInfo.value.data.unshift(data)
      callback(true)
    }
  }
}
function callBackAsset(data) {
  data.forEach((item) => {
    item.assetId = item.id
  })
  tableInfo.value.data = data.concat(tableInfo.value.data)
}
//删除资产
function removeAsset(selectRow = undefined) {
  if (selectRow) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'assetAssetReturnModify-com.slip.spd.entity.vo.asset.AssetReturnOrderDetailVO',
  }
  tableInfo.value.isSysGroup = false
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
      if (props.orderId) {
        getMain()
      }
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow: hidden;
}
</style>
